package com.pikaqiu.blog.controller;

import com.github.pagehelper.PageInfo;
import com.pikaqiu.blog.entity.Article;
import com.pikaqiu.blog.entity.ArticleComment;
import com.pikaqiu.blog.entity.ArticleType;
import com.pikaqiu.blog.entity.User;
import com.pikaqiu.blog.service.ArticleService;
import com.pikaqiu.blog.service.UserService;
import com.pikaqiu.blog.utils.DateUtil;
import com.pikaqiu.blog.utils.Result;
import com.sun.javafx.beans.annotations.Default;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;


/**
 * 文章控制类
 * @author 吕梁山
 * @date 2019/1/7
 */
@RestController
@RequestMapping("/api/article")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    @Autowired
    private UserService userService;

    @RequestMapping("/getArticlePage")
    public PageInfo<Article> getArticlePage(int pageNumber){
        return articleService.getArticlePage(pageNumber, 15);
    }

    @RequestMapping("/getArticle")
    public Article getArticle(int id){
        return articleService.getArticle(id);
    }

    @RequestMapping("/addArticleComment")
    public Result addArticleComment(ArticleComment articleComment, User user){
        Result result = new Result();
        User existerUser = userService.selectByEmail(user.getUserEmail());
        if(existerUser != null){
            articleComment.setUserId(existerUser.getId());
        } else {
            userService.insertUser(user);
            articleComment.setUserId(user.getId());
        }
        if(articleComment.getReplyTo() != null){
            articleComment.setType(2);
        } else {
            articleComment.setType(1);
        }
        articleComment.setCreateDate(new Date());
        articleService.addArticleComment(articleComment);
        result.setCode(0);
        result.setMsg("回复成功");
        return result;
    }

    @RequestMapping("/getArticleCommentPage")
    public PageInfo<ArticleComment> getArticleCommentPage(int pageNumber, int articleId){
        PageInfo<ArticleComment> articleCommentPage = articleService.getArticleCommentPage(articleId, pageNumber, 15);
        for (ArticleComment articleComment : articleCommentPage.getList()) {
            Date createDate = articleComment.getCreateDate();
            articleComment.setShowDate(DateUtil.getDateBeforeNow(createDate));
        }
        return articleCommentPage;
    }

    @RequestMapping("/getArticleTypeList")
    public List<ArticleType> getArticleTypeList(){
        return articleService.getArticleTypeList();
    }
}
